package com.example.OJ.controller;

import com.example.OJ.compile.Answer;
import com.example.OJ.compile.CommandUtil;
import com.example.OJ.compile.Question;
import com.example.OJ.compile.Task;
import com.example.OJ.dao.Problem;
import com.example.OJ.dao.ProblemDAO;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/execute")
public class CompileController {
    public static String mergeCode(String requestStr,String testCode){
        int pos = requestStr.lastIndexOf("}");
        if(pos == -1){
            return null;
        }
        String substr = requestStr.substring(0,pos);

        return "public "+substr+testCode+"\n}";
    }



    ProblemDAO problemDAO = new ProblemDAO();
    @RequestMapping("/compile")
    public Answer compile(@RequestBody Question question){
        Problem problem = problemDAO.selectOne(question.getId());
        Answer answer = new Answer();
        if(problem == null){
            answer.setError(3);
            answer.setReason("没有该题");
            return answer;
        }
        //测试代码
        String testCode = problem.getTestCode();
        //用户提交的代码
        String requestCode = question.getCode();
        String finalCode = mergeCode(requestCode,testCode);
        if(requestCode.equals("")){
            answer.setError(4);
            answer.setReason("提交代码不符合要求！");
            return answer;
        }
        question.setCode(finalCode);
        Task task = new Task();
        answer = task.compileAndRun(question);
        return answer;
    }
}
